<template>
  <div class="titan-card w-h-100">
    <section
      class="titan-card-header"
      :class="{
        'is-single': typeof props.title === 'string',
      }"
    >
      <div class="titan-card-header-left">
        <div
          v-if="typeof props.title === 'string'"
          class="titan-card-header__item"
        >
          <span>{{ props.title }}</span>
        </div>
        <template v-else>
          <span
            v-if="showScroll"
            class="scroll-button"
            @click.stop="handleScroll('left')"
          >
            <icon-left />
          </span>
          <div
            ref="titleWrapRef"
            class="titan-card-header__wrap"
          >
            <div
              v-for="item in props.title"
              :key="item.value"
              :class="{
                active: item.value === props.modelValue,
                'titan-card-header__item': true,
              }"
              @click="handleClick(item.value)"
            >
              <span>{{ item.label || "" }}</span>
            </div>
          </div>
          <span
            v-if="showScroll"
            class="scroll-button"
            @click.stop="handleScroll('right')"
          >
            <icon-right />
          </span>
        </template>
      </div>
      <div class="titan-card-header-right">
        <slot name="header" />
      </div>
    </section>
    <section class="titan-card-content">
      <slot />
    </section>
  </div>
</template>

<script setup lang="ts">
  import { watch, ref, onMounted, computed } from "vue";
  import { cardProps, ICardTitleItem } from "./card-types";

  defineOptions({
    name: "TitanCard",
  });

  const props = defineProps(cardProps);
  const emit = defineEmits<{
    (e: "update:modelValue", value: string): void;
  }>();

  const titleWrapRef = ref<HTMLDivElement>();

  const showScroll = computed(() => {
    if (!titleWrapRef.value) {
      return false;
    }
    return titleWrapRef.value.scrollWidth > titleWrapRef.value.clientWidth;
  });

  const handleClick = (value: string) => {
    emit("update:modelValue", value);
  };

  const handleScroll = (direction: string) => {
    if (direction === "left") {
      titleWrapRef.value && (titleWrapRef.value.scrollLeft += -50);
    } else {
      titleWrapRef.value && (titleWrapRef.value.scrollLeft += 50);
    }
  };

  watch(
    () => props.title,
    (value) => {
      if (typeof value === "string") {
        emit("update:modelValue", value);
      } else {
        const t = value as ICardTitleItem[];
        if (t.length) {
          if (!t.find((item) => item.value == props.modelValue)) {
            emit("update:modelValue", t[0].value);
          }
        }
      }
    }
  );

  onMounted(() => {
    console.log(titleWrapRef.value?.scrollWidth, titleWrapRef.value?.clientWidth);
  });
</script>
